import { seveToken, getToken, removeToken } from '@/utils/auth';
import { login } from '@/api/user';
import { Message } from 'element-ui';
import router from '@/router/index';

export default {
  namespaced: true,
  state: {
    token: getToken(),
  },
  getters: {
  },
  mutations: {
    seveToken(state, token) {
      state.token = token;
      seveToken(token);
    },
    removeToken(state) {
      state.token = null;
      removeToken();
    },
  },
  actions: {
    async login(context, form) {
      const res = await login();
      if (form.username === res.data.username && form.password === res.data.password && form.CAPTCHA === res.data.CAPTCHA) {
        Message({
          message: '登录成功',
          type: 'success',
          duration: 1200,
        });
        context.commit('seveToken', res.data.token);
        router.push('/');
      } else if (form.username !== res.data.username || form.password !== res.data.password) {
        Message({
          message: '账号或密码错误',
          type: 'error',
          duration: 1200,
        });
      } else if (form.CAPTCHA !== res.data.CAPTCHA) {
        Message({
          message: '验证码错误',
          type: 'error',
          duration: 1200,
        });
      }
    },
    logout(context) {
      context.commit('removeToken');
      router.push('/login');
    },
  },
};
